package com.xncoding.websocket.javax.demo1.Endpoint;

import com.xncoding.websocket.javax.demo1.Handler.MessageConfigurator;
import com.xncoding.websocket.javax.demo1.Handler.WsMessageDecoder;
import com.xncoding.websocket.javax.demo1.Handler.WsMessageEncoder;
import com.xncoding.websocket.javax.demo1.model.PersonMessage;
import com.xncoding.websocket.javax.demo1.model.PingMessage;
import com.xncoding.websocket.javax.demo1.model.SystemMessage;
import com.xncoding.websocket.javax.demo1.model.AbstractMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.HashMap;

@ServerEndpoint(value = "/message/{username}",
        encoders = {WsMessageEncoder.class},
        decoders = {WsMessageDecoder.class},
        subprotocols = {"gmsg"},
        configurator = MessageConfigurator.class)
@Component
public class GMessageListener {

    public static HashMap<String, String> sessions = new HashMap<>();
    private static Logger logger = LoggerFactory.getLogger(GMessageListener.class) ;

    private String username ;

    @OnOpen
    public void onOpen(Session session, EndpointConfig config, @PathParam("username") String username){
        this.username = username ;
        sessions.put(username, username) ;
        logger.info("【{}】用户进入, 当前连接数：{}", username, sessions.size()) ;
    }

    @OnClose
    public void onClose(Session session, CloseReason reason){
        sessions.remove(this.username) ;
        logger.info("用户【{}】, 断开连接, 当前连接数：{}", username, sessions.size()) ;
    }

    @OnMessage
    public void pongMessage(Session session, PongMessage message) {
        ByteBuffer buffer = message.getApplicationData() ;
        logger.debug("接受到Pong帧【这是由浏览器发送】：" + buffer.toString());
    }

    @OnMessage
    public void onMessage(Session session, AbstractMessage message) {
        if (message instanceof PingMessage) {
            logger.debug("这里是ping消息");
            return ;
        }
        if (message instanceof PersonMessage) {
            PersonMessage personMessage = (PersonMessage) message ;
            if (this.username.equals(personMessage.getToName())) {
                logger.info("【{}】收到消息：{}", this.username, personMessage.getContent());
            } else {
                try {
                    session.getBasicRemote().sendText("，你好！欢迎登陆系统");
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
            return ;
        }
        if (message instanceof SystemMessage) {
            logger.info("接受到消息类型为【系统消息】") ;
            return ;
        }
    }

    @OnError
    public void onError(Session session, Throwable error) {
        logger.error(error.getMessage()) ;
    }
}